package com.heima.user.interceotor;


import com.heima.model.user.pojo.ApUser;
import com.heima.utils.common.AppThreadLocalUtil;
import com.heima.utils.common.WmThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自媒体平台用户拦截器配置
 */
@Component
public class AppTokenInterceptor implements HandlerInterceptor {

    /**
     * 前置拦截--获取请求头中userId, 然后存入到当前线程中ThreadLocal
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.得到请求头header中的消息
        String userId = request.getHeader("userId");
        //2.判断请求头中的用户id是否存在,是否是匿名登录的用户（0）
        if (StringUtils.isNotBlank(userId) && !"0".equals(userId)){
            //存在，直接存入到当前线程中
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));

            AppThreadLocalUtil.setUser(apUser);
        }
        return true;
    }

    /**
     * 清除线程中的数据用户
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清除线程数据
        WmThreadLocalUtil.clear();
    }

}
